<script setup lang="ts">
import { queryServerConfigByLevel } from '@/api';
import { getServiceContent } from '@/tools/care';
import type { MutipleType, ServiceContentConfig } from '@/types';
import { isEmpty } from 'radash';
import { reactive, ref, watch } from 'vue';


const props = defineProps<{
	level: MutipleType
	packageID?: MutipleType
}>();

const emit = defineEmits(['change']);


const configs = ref<Array<{
	TagName: string
	Levels: Array<{
		SettingLevelID: number
		SettingName: string
		Selected: boolean
		SettingID: number
	}>
}>>([]);

const checkMap = reactive<ServiceContentConfig[]>([]);

const getConfig = () => {
	queryServerConfigByLevel(Number(props.level), props.packageID).then(res => {
		const settings = res.Data?.Settings || [];
		checkMap.length = 0;
		for (const item of settings) {
			const checkedList = [];
			const all = [];
			const settingIdMap: Record<string, number> = {};
			for (const v of item.Levels) {
				if (v.Selected) {
					checkedList.push(v.SettingID);
				}
				all.push(v.SettingID);
				settingIdMap[v.SettingID] = v.SettingLevelID;
			}
			checkMap.push({
				indeterminate: checkedList.length > 0 && checkedList.length < all.length,
				checkAll: checkedList.length === all.length,
				checkedList,
				all,
				tagID: item.TagID,
				settingIdMap
			});
		}
		configs.value = settings;
	});
};

watch(() => props.level, (val) => {
	if (isEmpty(val)) return;
	getConfig();
}, {
	immediate: true,
});

const getOptions = (list: any[]) => {
	return list.map(v => ({
		label: v.SettingName,
		value: v.SettingID
	}));
};

const checkAll = (e: any, index: number) => {
	checkMap[index].indeterminate = false;
	checkMap[index].checkAll = e.target?.checked || false;
	checkMap[index].checkedList = e.target?.checked ? checkMap[index].all.slice() : [];
	emit('change', getServiceContent(checkMap));
};

const checkChange = (e: any, index: number) => {
	checkMap[index].indeterminate = e?.length > 0 && e.length < checkMap[index].all.length;
	checkMap[index].checkAll = e?.length === checkMap[index].all.length;
	emit('change', getServiceContent(checkMap));
};

</script>

<template>
	<div class="mt5">
		<div class="mb10">服务项</div>
		<div v-for="(item, index) in configs" class="mb15" :key="index">
			<div class="mb5">
				{{ item.TagName }}
				<a-checkbox @change="(e: any) => checkAll(e, index)" v-model:checked="checkMap[index].checkAll" :indeterminate="checkMap[index].indeterminate" class="ml10">全选</a-checkbox>
			</div>
			<a-checkbox-group @change="(e: any) => checkChange(e, index)" v-model:value="checkMap[index].checkedList" :options="getOptions(item.Levels)"></a-checkbox-group>
		</div>
	</div>
</template>
<style scoped></style>
